<template>
  <!-- display外出情况 -->
  <div class="outgoing-count">
    <div class="header-container">
      <div class="module-title">
        外出人数
        <button
          class="info-btn"
          @mouseenter="showTooltip"
          @mouseleave="hideTooltip">
          <i class="el-icon-reading"></i>
        </button>
        <!-- 悬停提示框 -->
        <div
          v-show="tooltipVisible"
          class="tooltip-box"
          :style="tooltipStyle">
          {{ outingInfoText }}
        </div>
      </div>
    </div>
    <div class="content-container">
      <div class="chart-container" ref="pieChart"></div>
      <div class="legend-container">
        <div class="legend-title">{{ latestDate }} 外出统计</div>
        <div class="legend-item"
             v-for="(item, index) in legendItems"
             :key="index"
             :class="{ active: activeIndex === index }"
             @mouseenter="highlightSegment(index)"
             @mouseleave="resetHighlight">
          <div class="color-block" :style="{ backgroundColor: item.color }"></div>
          <div class="legend-info">
            <div class="legend-name">{{ item.name }}</div>
            <div class="legend-value">{{ item.value }}人</div>
          </div>
        </div>
      </div>
    </div>
    <div class="data-summary">
      <div class="summary-item">
        <div class="summary-label">全对总人数</div>
        <div class="summary-value">{{ totalStudents }}</div>
      </div>
      <div class="summary-item">
        <div class="summary-label">在校人数</div>
        <div class="summary-value">{{ inSchoolCount }}</div>
      </div>
      <div class="summary-item">
        <div class="summary-label">1组外出</div>
        <div class="summary-value">{{ grade1Count }}</div>
      </div>
      <div class="summary-item">
        <div class="summary-label">2组外出</div>
        <div class="summary-value">{{ grade2Count }}</div>
      </div>
      <div class="summary-item">
        <div class="summary-label">3组外出</div>
        <div class="summary-value">{{ grade3Count }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'OutgoingCount',
  data() {
    return {
      pieChart: null,
      totalStudents: 233, // 全对总人数
      outgoingData: [],
      latestDate: '',
      grade1Count: 0,
      grade2Count: 0,
      grade3Count: 0,
      inSchoolCount: 0,
      activeIndex: -1, // 当前高亮的图例索引
      chartColors: ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76'], // 饼图颜色
      legendItems: [], // 图例项数据
      // 提示框相关
      tooltipVisible: false,
      outingInfoText: '',
      tooltipStyle: {
        position: 'absolute',
        top: '35px',
        left: '120px',
        zIndex: 1000,
        width: '350px',
        height: '280px'
      }
    };
  },
  mounted() {
    this.loadOutingInfoText();
    this.loadOutgoingData();
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
    if (this.pieChart) {
      this.pieChart.dispose();
    }
  },
  methods: {
    async loadOutgoingData() {
      try {
        const response = await this.$displayapi.getOutCount();
        console.log('API返回内容', response); // 打印返回内容方便调试

        // 兼容 code 为字符串或数字
        if (!response || (response.code !== '200' && response.code !== 200) || !response.data) {
          throw new Error('API返回数据格式错误');
        }

        const data = response.data;

        // 用后端返回的总人数
        this.totalStudents = parseInt(data.countStudent) || 0;

        // 初始化各组外出人数
        this.grade1Count = 0;
        this.grade2Count = 0;
        this.grade3Count = 0;

        // 处理各组外出数据，兜底处理outDTOList
        const outList = Array.isArray(data.outDTOList) ? data.outDTOList : [];
        outList.forEach(item => {
          const count = parseInt(item.groupCount) || 0;
          switch(item.groupName) {
            case '1':
              this.grade1Count = count;
              break;
            case '2':
              this.grade2Count = count;
              break;
            case '3':
              this.grade3Count = count;
              break;
          }
        });

        // 计算在校人数
        const totalOutgoing = this.grade1Count + this.grade2Count + this.grade3Count;
        this.inSchoolCount = this.totalStudents - totalOutgoing;

        // 更新图表
        this.initChart();
      } catch (error) {
        console.error('外出数据加载失败:', error);
        this.$message.error('加载数据失败');
      }
    },

    // 加载外出情况说明文本
    async loadOutingInfoText() {
      try {
        const response = await fetch('/tltl.txt');
        if (response.ok) {
          const text = await response.text();
          // 提取"1、"后面的文本，直到下一个序号或文件结束
          const regex = /1、(.*?)(?=\s*\d+、|$)/s;
          const match = text.match(regex);
          if (match && match[1]) {
            this.outingInfoText = match[1].trim();
            console.log('外出情况说明文本:', this.outingInfoText);
          } else {
            console.error('未找到外出情况说明文本');
            this.outingInfoText = '数据总览：外出人数：在校率：连队应当严格按照比例控制休息日和节假日请假外出人数。连队外出人数占实力数的比例：…其他部队通常不超过15%。';
          }
        } else {
          console.error('加载外出情况说明文本失败');
          this.outingInfoText = '数据总览：外出人数：在校率：连队应当严格按照比例控制休息日和节假日请假外出人数。连队外出人数占实力数的比例：…其他部队通常不超过15%。';
        }
      } catch (error) {
        console.error('加载外出情况说明文本出错:', error);
        this.outingInfoText = '数据总览：外出人数：在校率：连队应当严格按照比例控制休息日和节假日请假外出人数。连队外出人数占实力数的比例：…其他部队通常不超过15%。';
      }
    },

    parseCSV(csvText) {
      // 处理可能的回车符和换行符
      const normalizedText = csvText.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
      const lines = normalizedText.split('\n');
      const headers = lines[0].split(',').map(h => h.trim());

      return lines.slice(1).filter(line => line.trim()).map(line => {
        // 处理CSV中的引号包裹的值
        let inQuotes = false;
        let currentValue = '';
        const values = [];

        for (let i = 0; i < line.length; i++) {
          const char = line[i];

          if (char === '"') {
            inQuotes = !inQuotes;
          } else if (char === ',' && !inQuotes) {
            values.push(currentValue);
            currentValue = '';
          } else {
            currentValue += char;
          }
        }

        // 添加最后一个值
        values.push(currentValue);

        const record = {};
        headers.forEach((header, index) => {
          let value = values[index] || '';
          // 处理引号包裹的值
          if (value.startsWith('"') && value.endsWith('"')) {
            value = value.substring(1, value.length - 1);
          }
          record[header] = value.trim();
        });

        return record;
      });
    },

    initChart() {
      this.pieChart = echarts.init(this.$refs.pieChart);

      const totalOutgoing = this.grade1Count + this.grade2Count + this.grade3Count;

      // 主饼图数据
      const mainPieData = [
        { value: this.inSchoolCount, name: '在校人数' },
        { value: this.grade1Count, name: '1组外出' },
        { value: this.grade2Count, name: '2组外出' },
        { value: this.grade3Count, name: '3组外出' }
      ];

      // 外出比例饼图数据
      const outgoingPieData = [
        { value: this.grade1Count, name: '1组' },
        { value: this.grade2Count, name: '2组' },
        { value: this.grade3Count, name: '3组' }
      ];

      // 初始化图例数据
      this.legendItems = mainPieData.map((item, index) => ({
        name: item.name,
        value: item.value,
        color: this.chartColors[index]
      }));

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            return `${params.seriesName} <br/>${params.name}: ${params.value}人 (${params.percent}%)`;
          },
          backgroundColor: 'rgba(19, 25, 47, 0.8)',
          borderColor: '#68d8fe',
          borderWidth: 1,
          textStyle: {
            color: '#d3d6dd',
            fontSize: 14
          }
        },
        legend: {
          show: false
        },
        series: [
          {
            name: '人数分布',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['35%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#13192f',
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'center',
              formatter: () => {
                const percentage = Math.round((this.inSchoolCount / this.totalStudents) * 100);
                return `${percentage}%\n在校率`;
              },
              fontSize: 20,
              fontWeight: 'bold',
              color: '#68d8fe'
            },
            emphasis: {
              scale: true,
              scaleSize: 12,
              itemStyle: {
                shadowBlur: 20,
                shadowColor: 'rgba(104, 216, 254, 0.5)'
              }
            },
            labelLine: {
              show: false
            },
            data: mainPieData,
            color: this.chartColors
          },
          {
            name: '外出比例',
            type: 'pie',
            radius: ['25%', '35%'],
            center: ['75%', '25%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 5,
              borderColor: '#13192f',
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'center',
              formatter: () => {
                return `${totalOutgoing}人\n外出`;
              },
              fontSize: 14,
              fontWeight: 'bold',
              color: '#68d8fe'
            },
            emphasis: {
              scale: true,
              scaleSize: 10,
              itemStyle: {
                shadowBlur: 20,
                shadowColor: 'rgba(104, 216, 254, 0.5)'
              }
            },
            labelLine: {
              show: false
            },
            data: outgoingPieData,
            color: this.chartColors.slice(1) // 使用主饼图除了"在校"之外的颜色
          }
        ]
      };

      this.pieChart.setOption(option);

      // 添加鼠标悬停事件监听
      this.pieChart.on('mouseover', { seriesIndex: 0 }, (params) => {
        this.highlightSegment(params.dataIndex);
      });

      this.pieChart.on('mouseout', { seriesIndex: 0 }, () => {
        this.resetHighlight();
      });


    },

    // 高亮饼图片段
    highlightSegment(index) {
      this.activeIndex = index;

      // 高亮饼图对应片段
      const highlightAction = {
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: index
      };
      this.pieChart.dispatchAction(highlightAction);
    },

    // 重置高亮状态
    resetHighlight() {
      this.activeIndex = -1;

      // 取消饼图所有高亮
      const downplayAction = {
        type: 'downplay',
        seriesIndex: 0
      };
      this.pieChart.dispatchAction(downplayAction);
    },

    resizeChart() {
      if (this.pieChart) {
        this.pieChart.resize();
      }
    },

    // 显示提示框
    showTooltip() {
      this.tooltipVisible = true;
    },

    // 隐藏提示框
    hideTooltip() {
      this.tooltipVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.outgoing-count {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .header-container {
    display: flex;
    justify-content: flex-start;
    padding-left: 20px;
    margin-bottom: 10px;
    margin-top: 10px;
  }

  .module-title {
    font-size: 22px;
    color: #68d8fe;
    font-weight: bold;
    text-align: left;
    position: relative;
    z-index: 1;
    display: flex;
    align-items: center;
    gap: 10px;

    .info-btn {
      background: rgba(104, 216, 254, 0.2);
      border: 1px solid rgba(104, 216, 254, 0.5);
      border-radius: 4px;
      color: #68d8fe;
      cursor: pointer;
      padding: 4px 8px;
      font-size: 16px;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background: rgba(104, 216, 254, 0.3);
        border-color: rgba(104, 216, 254, 0.8);
        color: #ffffff;
        transform: scale(1.05);
      }

      i {
        font-size: 14px;
      }
    }

    .tooltip-box {
      background: rgba(19, 25, 47, 0.95);
      border: 1px solid rgba(104, 216, 254, 0.5);
      border-radius: 6px;
      padding: 20px 24px;
      color: #d3d6dd;
      font-size: 16px;
      line-height: 1.8;
      width: 350px;
      height: 280px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
      backdrop-filter: blur(10px);
      word-wrap: break-word;
      white-space: normal;
      overflow-y: auto;
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
      text-align: left;

      &::before {
        content: '';
        position: absolute;
        top: -6px;
        left: 20px;
        width: 0;
        height: 0;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
        border-bottom: 6px solid rgba(104, 216, 254, 0.5);
      }

      &::after {
        content: '';
        position: absolute;
        top: -5px;
        left: 21px;
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-bottom: 5px solid rgba(19, 25, 47, 0.95);
      }
    }
  }

  .content-container {
    display: flex;
    flex: 1;
    min-height: 300px; /* 增加内容区域高度 */
    margin-bottom: 15px;
  }

  .chart-container {
    width: 50%;
    min-height: 300px; /* 与内容区域高度保持一致 */
  }

  .legend-container {
    width: 50%;
    padding-left: 20px;
    display: flex;
    flex-direction: column;

    .legend-title {
      font-size: 20px;
      color: #d3d6dd;
      margin-bottom: 20px;
      text-align: center;
      font-weight: bold;
    }

    .legend-item {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      padding: 8px 12px;
      border-radius: 6px;
      transition: all 0.3s ease;
      cursor: pointer;

      &:hover, &.active {
        background-color: rgba(104, 216, 254, 0.1);
        transform: translateX(5px);
      }

      .color-block {
        width: 16px;
        height: 16px;
        border-radius: 4px;
        margin-right: 12px;
      }

      .legend-info {
        flex: 1;

        .legend-name {
          font-size: 18px;
          color: #d3d6dd;
          margin-bottom: 4px;
        }

        .legend-value {
          font-size: 20px;
          font-weight: bold;
          color: #68d8fe;
        }
      }
    }
  }

  .data-summary {
    display: flex;
    justify-content: space-around;
    padding: 15px 0;
    margin-top: auto; /* 将数据汇总区域推到底部 */
    border-top: 1px solid rgba(104, 216, 254, 0.3);
    background-color: rgba(19, 25, 47, 0.5);
    border-radius: 4px;
    margin-bottom: 10px; /* 添加底部间距 */

    .summary-item {
      text-align: center;
      padding: 0 10px;

      .summary-label {
        font-size: 18px;
        color: #d3d6dd;
        margin-bottom: 8px;
      }

      .summary-value {
        font-size: 22px;
        font-weight: bold;
        color: #68d8fe;
      }
    }
  }
}
</style>
